#include "../muduo/proto/pro.pb.h"
#include "../muduo/proto/codec.h"
#include "../muduo/proto/dispatcher.h"

#include <iostream>
#include <unordered_map>
#include <string>
#include <memory>
#include "Logging.h"
#include "Mutex.h"
#include "TcpClient.h"
#include "EventLoop.h"
#include "TcpConnection.h"
#include "CountDownLatch.h"
#include "EventLoopThread.h"

using namespace std;
using namespace muduo::net;

class Client
{
public:
    typedef shared_ptr<google::protobuf::Message> MessagePtr;
    typedef shared_ptr<pro::AddResponse> AddResponsePtr;
    typedef shared_ptr<pro::TranslateResponse> TranslateResponsePtr;
    Client(const string &svr_ip, int svr_port)
        : _latch(1), _client(_loopthread.startLoop(), muduo::net::InetAddress(svr_ip, svr_port), "Client"),
          _dispatcher(std::bind(&Client::onUnknownMessage, this, placeholders::_1, placeholders::_2, placeholders::_3)),
          _codec(std::bind(&ProtobufDispatcher::onProtobufMessage, &_dispatcher, placeholders::_1, placeholders::_2, placeholders::_3))
    {
        // 注册响应处理回调
        _dispatcher.registerMessageCallback<pro::TranslateResponse>(std::bind(&Client::onTranslate, this,
                                                                              placeholders::_1, placeholders::_2, placeholders::_3)); // TranslateResponse类型消息：onTranslate回调
        _dispatcher.registerMessageCallback<pro::AddResponse>(std::bind(&Client::onAdd, this,
                                                                        placeholders::_1, placeholders::_2, placeholders::_3)); // AddResponse类型消息：onAdd回调
        // 参数绑定回调
        _client.setConnectionCallback(std::bind(&Client::onConnection, this, std::placeholders::_1));
        _client.setMessageCallback(std::bind(&ProtobufCodec::onMessage, &_codec, placeholders::_1, placeholders::_2, placeholders::_3));
    }
    void connect()
    {
        _client.connect(); // 连接服务器
        _latch.wait();     // 主线程进入阻塞，等待连接成功后，调用onConnection回调唤醒
    }
    bool send(const google::protobuf::Message &message)
    {
        if (_server_conn->connected()) // 检测连接状态正常
        {
            _codec.send(_server_conn, message); // 发送
            return true;
        }
        return false;
    }
    void Translate(const string &msg)
    {
        // 构建请求并发送
        pro::TranslateRequest req;
        req.set_msg(msg);
        send(req);
    }
    void Add(int num1, int num2)
    {
        pro::AddRequest req;
        req.set_num1(num1);
        req.set_num2(num2);
        send(req);
    }

private:
    void onUnknownMessage(const muduo::net::TcpConnectionPtr &conn, const MessagePtr &message, muduo::Timestamp)
    { // 收到未定义的消息类型时，回调处理
        cout << "onUnknownMessage:" << message->GetTypeName() << endl;
    }
    void onTranslate(const muduo::net::TcpConnectionPtr &conn, const TranslateResponsePtr &message, muduo::Timestamp)
    {
        cout << "翻译结果：" << message->msg() << endl;
    }
    void onAdd(const muduo::net::TcpConnectionPtr &conn, const AddResponsePtr &message, muduo::Timestamp)
    {
        cout << "加法结果：" << message->result() << endl;
    }
    void onConnection(const muduo::net::TcpConnectionPtr &conn)
    { // 成功连接服务器时回调
        if (conn->connected())
        {
            _latch.countDown(); // 唤醒主线程的阻塞
            _server_conn = conn;
        }
        else
        {
            // 连接关闭
            _server_conn.reset(); // 重置连接
        }
    }

private:
    muduo::CountDownLatch _latch;              // 防止连接还没建立成功，就使用未定义的连接对象
    muduo::net::EventLoopThread _loopthread;   // 客户端也需要事件监控，但不能像服务器那样死循环阻塞监控，而是创建线程监控，创建成功后自动开启循环监控
    muduo::net::TcpClient _client;             // 客户端类
    muduo::net::TcpConnectionPtr _server_conn; // 服务器连接对象

    ProtobufDispatcher _dispatcher; // 请求分发器：注册请求处理函数
    ProtobufCodec _codec;           // protobuf协议处理器：针对数据协议处理
};

int main()
{
    Client client("127.0.0.1", 8080);
    client.connect();

    // 发送两种不同类型的请求
    client.Add(1, 2);
    client.Translate("abc");
    client.Translate("OK");
    client.Translate("absaiosc");
    sleep(1);
    return 0;
}